#!/bin/bash

source commonlib.sh

script_root="/root/script"

if [ "$(arch)" == "aarch64" ]; then
    target_arch="arm64"
else
    target_arch="amd64"
fi

# 配置 hosts 映射
function hosts_setup() {
    hosts_path=$1
    if [ -z ${hosts_path+x} ]; then
        log ERROR "Repo file do not exist"
        exit 1
    fi
    cp /etc/hosts /etc/hosts.bk
    cat $hosts_path >> /etc/hosts
}

# 配置 yum 源,并检测是否work
function yum_setup() {
    repo_path=$1
    if [ -z ${repo_path+x} ]; then
        log ERROR "Repo file do not exist"
        exit 1
    fi

    cp $repo_path /etc/yum.repos.d/
    if yum makecache; then
        log INFO "Yum is ready to work"
    else
        log ERROR "Yum is not ready, please check Internet"
    fi
}

function docker_install() {
    yum install docker -y
}

function docker_config() {
    echo "INSECURE_REGISTRY=\"--insecure-registry k8s.gcr.io --insecure-registry quay.io\"" >> /etc/sysconfig/docker
    systemctl daemon-reload && systemctl restart docker
}

function common_install() {
    yum install -y wget git curl tar
}


# crictl install
function crictl_install() {
    crictl_version="v1.20.0"
    if [ ! -f ${script_root}/crictl-${crictl_version}-linux-${target_arch}.tar.gz ]; then
        wget --no-check-certificate -P $script_root https://github.com/kubernetes-sigs/cri-tools/releases/download/${crictl_version}/crictl-${crictl_version}-linux-${target_arch}.tar.gz
        tar zxvf ${script_root}/crictl-${crictl_version}-linux-${target_arch}.tar.gz -C /usr/local/bin
    fi
}

# cni-plugin install
function cni_plugin_install() {
    cni_plugin_version="v0.9.0"
    if [ ! -f ${script_root}/cni-plugins-linux-${target_arch}-${cni_plugin_version}.tgz ]; then
        wget --no-check-certificate -P ${script_root} https://github.com/containernetworking/plugins/releases/download/${cni_plugin_version}/cni-plugins-linux-${target_arch}-${cni_plugin_version}.tgz
        mkdir -p /opt/cni/bin
        tar -zxvf ${script_root}/cni-plugins-linux-${target_arch}-${cni_plugin_version}.tgz -C /opt/cni/bin
    fi
}

function k8s_install() {
    yum install kubernetes-* -y
    systemctl enable kubelet --now
    crictl_install
    cni_plugin_install
}


function k8s_common_config() {
    systemctl stop firewalld
    systemctl disable firewalld
    setenforce 0
    cat << EOF > /etc/sysctl.d/k8s.conf
    net.bridge.bridge-nf-call-ip6tables = 1
    net.bridge.bridge-nf-call-iptables = 1
    net.ipv4.ip_forward = 1
    vm.swappiness=0
EOF
    sysctl -p /etc/sysctl.d/k8s.conf
    modprobe br_netfilter
    swapoff -a
}

function k8s_master_config() {
    k8s_common_config
}

function k8s_worker_config() {
    k8s_common_config
}

function k8s_config() {
    target_role=$1
    if [ "$target_role" == "master" ]; then
        k8s_master_config
    else
        k8s_worker_config
    fi
}

hosts_setup "$script_root/hosts"
yum_setup "$script_root/openEuler.repo"
common_install
docker_install
docker_config
k8s_install
k8s_common_config
